<template>
  <common-edit-dialog
    :title="title"
    :visible.sync="open"
    @cancel="cancel"
    @submit="submitForm"
    :buttonLoading="buttonLoading"
  >
    <el-form ref="form" :model="form" label-width="80px" @submit.native.prevent>
      <el-tree
        :data="typeList"
        show-checkbox
        default-expand-all
        node-key="typeId"
        ref="tree"
        highlight-current
        :check-strictly="true"
        :props="defaultProps"
        @check-change="handleCheckChange"
      >
      </el-tree>
    </el-form>
  </common-edit-dialog>
</template>

<script>
import {
  ruleConfigAdd,
  ruleConfigEdit,
} from "@/api/datascan/ruleVariable/variableConfig";

import { listType } from "@/api/datascan/datatype/type";

export default {
  data() {
    return {
      buttonLoading: false,
      title: "设置数据分类",
      open: false,
      defaultProps: {
        children: "children",
        label: "typeName",
      },
      typeList: [],
      form: {
        typeId: "",
        typeName: "",
      },
    };
  },
  props: {
    currentCheckedIds: {
      type: Array,
      default: () => [],
    },
    dbId: {
      type: Number,
      default: 0,
    },
  },
  mounted() {
    listType().then((res) => {
      if (res && res.code === 200) {
        this.open = true;
        this.typeList = res.data;
        this.setDisabledOption(this.typeList);
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(this.currentCheckedIds);
        });
      }
    });
  },
  methods: {
    handleCheckChange(data, checked) {
      if (checked) {
        this.$refs.tree.setCheckedKeys([data.typeId]);
      }
    },

    setDisabledOption(data) {
      if (data.length > 0) {
        data.forEach((f) => {
          f.disabled = f.children && f.children.length > 0;
          if (f.children && f.children.length > 0) {
            this.setDisabledOption(f.children);
          }
        });
      }
    },

    submitForm() {
      console.log(this.$refs.tree.getCheckedKeys());
      return;
      this.buttonLoading = true;
      ruleConfigEdit({
        typeId: this.$refs.tree.getCheckedKeys(),
        dbId: this.dbId
      })
        .then((res) => {
          if (res && res.code === 200) {
            this.$emit("submitForm");
            this.$GlobalSuccessMessage("操作成功");
            this.open = false;
          } else {
            this.$GlobalErrorConfirm("操作失败", res.msg);
          }
        })
        .catch(() => {})
        .finally(() => {
          this.buttonLoading = false;
        });
    },
    cancel() {
      this.open = false;
    },
  },
};
</script>

<style lang="scss" scoped></style>
